using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace TDUnit.TestDataParsers.XmlParser
{
    public class ImportElementProcessor : ElementProcessorBase, IXmlTestDataProcessor
    {
        private XNamespace datasetNamespace;

        public void Process(XDocument document)
        {
            if(document.Root == null) return;

            datasetNamespace = document.Root.GetDefaultNamespace();

            var imports = from import in document.Root.Elements(datasetNamespace + "Import") select import;
            foreach (var import in imports)
            {
                ProcessImportElement(import);
            }
        }

        #region Helper methods

        private void ProcessImportElement(XElement import)
        {
            var importFileAttribute = import.Attribute("File");
            if (importFileAttribute == null)
                throw new XmlTestDataParserException("Import elements must contain a File attribute", import);

            var importedDoc = XDocument.Load(importFileAttribute.Value);
            AssertRootElementIsValid(importedDoc);

            var root = importedDoc.Root;
            if (root == null) return;

            SetNamespacesOnImportedElements(root.Elements());

            import.ReplaceWith(root.Elements());
        }

        private void SetNamespacesOnImportedElements(IEnumerable<XElement> elements)
        {
            if (elements == null)
                return;

            foreach (var element in elements)
            {
                if (element.Name.Namespace == datasetNamespace) continue;

                element.Name = datasetNamespace + element.Name.LocalName;
                SetNamespacesOnImportedElements(element.Elements());
            }
        }

        #endregion
    }
}